<template>
	<view class="all-box containers" style="margin-bottom:106rpx;">
		<view v-if="netWorkType!='none'">
			<tui-skeleton v-if="skeletonShow" backgroundColor="#fafafa" borderRadius="10rpx"></tui-skeleton>
			<view class="container tui-skeleton">
				<!-- 头部 -->
				<view class="user-info bg-body2 font-white padleft15 padbottom15 padtop30">
					<view class="flex-box">
						<view class="flex-start-box">
							<image class="head-img" v-if="avatarUrl" :src="avatarUrl" mode="widthFix"></image>
							<view class="font14 padbottom5 over-ellipsis" style="width:100rpx;margin-left: 20rpx;">{{nickName}}</view>
							<!-- <image class="head-img"  src="../../../static/img/healthy-default-head.png" mode="widthFix"></image> -->

							<view  v-if="isBind" class="padleft10" style="border-left:1rpx solid #ffffff59;">
								<view class="font14 padbottom5 over-ellipsis" style="max-width:136rpx;">{{userName}}</view>
								<view class="font12 font-white" >年龄 {{userAge || '-'}}岁</view>
							</view>
							<view  v-if="isBind" @tap="changeRole"><text class="iconfont padleft15 font-white font17">&#xe6c5;</text></view>
						</view>
						<view class="" v-if="!isBind">
							<!-- <view @tap="getList()" class="update-btn font14  font-gray">
								<text class="iconfont padright5">&#xe6c2;</text>
								更新数据
							</view> -->
							<view @tap="bindEquip" class="update-btn font14  font-gray">
								<text class="iconfont padright5">&#xe6c4;</text>
								绑定设备
							</view>
						</view>
					</view>
				</view>
				<!-- 头部end -->
				<!-- 检测结果 -->
				<view class="test-result pad-all15 bg-white">

					<view class="flex-box">
						<view v-if="data.list.check.sp" class="flex-start-box">
							<view class="font16 font-bold">最近一次测量数据</view>
							<view v-if="data.list.check.sp<140" class="tag normal font-white font12">正常</view>
							<view v-else class="tag danger font-white font12">异常</view>
							<!-- sp大于等于140都是异常 -->
						</view>
						<view v-else class="font16 font-bold">暂无数据</view>

						<view @tap="testRecord">
							<text class="font12 font-gray2">历史记录</text>
							<text class="iconfont padleft5 font12 font-gray">&#xe62b;</text>

						</view>
					</view>
					<view v-if="data.list.check.sp" class="date-time font-gray font12 padtop5">
						{{data.list.check.create_time}}
					</view>
					<view class="flex-box padtop15 result-data padbottom15">
						<view class="v-item text-center">
							<view v-if="data.list.check.sp">
								<view :class="[data.list.check.sp<140 ? 'font24 ' : 'font24 danger-color']">{{data.list.check.sp}}</view>
								<view class="font-gray2 font12">收缩压</view>
								<view class="font-gray2 font12">mmHg</view>
							</view>
							<view v-else class="no-data-style">
								- -
							</view>

						</view>
						<view class="v-item text-center center">
							<view v-if="data.list.check.dp">
								<view class="font24  ">{{data.list.check.dp}}</view>
								<view class="font-gray2 font12">舒张压</view>
								<view class="font-gray2 font12">mmHg</view>
							</view>
							<view v-else class="no-data-style">
								- -
							</view>
						</view>
						<view class="v-item text-center">
							<view v-if="data.list.check.dp">
								<view class="font24  ">{{data.list.check.heart}}</view>
								<view class="font-gray2 font12">脉搏</view>
								<view class="font-gray2 font12">bpm</view>
							</view>
							<view v-else class="no-data-style">
								- -
							</view>
						</view>
					</view>
				</view>
				<!-- 检测结果end -->

				<!-- 数据解读 -->
				<view class="help-tips padleft15 padright15 padbottom15 bg-white">
					<view class="flex-box">
						<text class="font16 font-bold">今日数据解读</text>
						<view @tap="introduction">
							<text class="iconfont green-color font12 padright5">&#xe651;</text>
							<text class="green-color font12">测试说明</text>
						</view>
					</view>
					<view class="tips pad-all10 margintop15 border-radius4">
						{{data.list.desc || '目前暂无数据，请绑定设备后测试并同步数据'}}
					</view>

				</view>
				<view class="week-trend  padbottom15 bg-white padtop15">
					<view class="flex-box padleft15 padright15">
						<text class="font16 font-bold">血压波动趋势</text>
						<view>
							<text class="circle-icon margin-right5"></text> <text class="font12" font12>高压</text>
							<text class="circle-icon low margin-right5 marginleft15"></text> <text class="font12">低压</text>
						</view>
					</view>

					<view class="f2_container">
						 <canvas  type="2d" class="f2-canvas"    @touchStart="touchStart" @touchMove="touchMove" @touchEnd="touchEnd" />

					</view>
					<view class="viewMore font12 text-center"  v-if="showEchart">
						<view class="btn  pad-all10 bg-body2 font-white" @tap="moreData">查看更多</view>
					</view>
				</view>

				<!-- 健康计划 -->
				<view v-if="loginStatus" @tap="enableHealthyPlan" class="healthy-plan-banner margintop10 margin-bottom10">
					<image class="publicImg" :src="OSS_HOST+'img/healthy-plan-banner.png'" mode="widthFix"></image>
				</view>
				<!-- 数据解读end -->
				<!-- 文章 推荐 -->
				<view class="article bg-white padtop15" v-if="loginStatus">
					<view class="flex-box">
						<view class="font16 font-bold left-line padleft15 margin-bottom15">文章推荐</view>
						<view @tap="pageArticleList">
							<text class="font12 font-gray2">查看更多</text>
							<text class="iconfont padleft5 font12 font-gray">&#xe62b;</text>
						</view>
					</view>

					<view @tap="pageArticleDetail(item.id)" class="flex-start-box row margin-bottom15 padright15 border-bottom" :key='item.id'
					 v-for="(item,index) in data.list.article">
						<view class="padleft15 content">
							<view class="over-ellipsis-two title padright15">
								{{item.title}}
							</view>
							<view class="desc font12 font-gray2 padtop10">
								<text class="padright15">{{item.view_count}}看过</text>
								<text>{{item.praise_num}}点赞</text>

							</view>
						</view>
						<view class="article-img-box">
							<image class="article-img" :src="item.image" mode="widthFix"></image>
						</view>


					</view>
				</view>

				<!-- 文章推荐end -->

				<!-- 底部 -->


			<!-- 	<cover-view class="fix-foot" v-show="showBottomMenu">
					<cover-view class="flex-box" style="flex-wrap: nowrap;">
						<cover-view @tap="toIndex()" class="item width-half" style="border-right: 1rpx solid #DDDDDD;">
							<cover-view class="iconfont">
								<cover-image style="width:30rpx;margin-bottom: 4rpx;" :src="OSS_HOST+'img/healthy-foot-nav1.png'"></cover-image>
							</cover-view>
							<cover-view class="font12">
								首页
							</cover-view>

						</cover-view>
						<cover-view @tap="toManager" class="item width-half">
							<cover-view>
								<cover-image style="width:30rpx;margin-bottom: 4rpx;" :src="OSS_HOST+'img/healthy-foot-nav2.png'"></cover-image>

							</cover-view>
							<cover-view class="font12">
								管理
							</cover-view>

						</cover-view>
					</cover-view>
				</cover-view> -->

			</view>
		</view>
		<!-- 切换角色弹窗 -->
		<uni-popup id="roles" ref='roles' type="bottom" :mask-click="false">
			<view style="background:#fff;">
				<view class="text-center" @tap="selectRole(item)" v-for="(item,index) in data.user_member" style="line-height: 90rpx;border-bottom: 1rpx solid #EEEEEE;">
					{{item.nickname}}
				</view>

				<view @click="cancelRole" class="text-center cancel">取消</view>
			</view>

		</uni-popup>
		<!-- 切换角色 -->
		<!-- 悬浮弹窗 -->
		  <view   class="manager-button index-button" style="right: 20rpx;left: inherit;">
			<view style="position: relative;">
				<tui-bubble-popup direction="bottom" position="absolute" width="140rpx" top="-110rpx" :mask="false" :show="showTip"  triangleBottom="-24rpx"
				 backgroundColor="rgba(0, 0, 0, 0.4)" triangleLeft="90rpx" left="-52rpx">
					<view class="tui-chat-text" style="padding: 10rpx;font-size: 30rpx;" @tap="closeTip" >查看家人 健康数据</view>
				</tui-bubble-popup>
			</view>
			<image @tap="toFamily" :src="OSS_HOST+'health/family_icon.png'" style="width: 112rpx; height: 112rpx !important;"></image>
		 
		</view>

		<view @tap="toManager" class="manager-button" style="right: 20rpx;left: inherit;">
				<image :src="OSS_HOST+'health/manage_icon.png'" style="width: 112rpx; height: 112rpx !important;"></image>
		</view>  
		<!-- -->
		<!-- 登录弹窗 -->
		<uni-popup-vlogin id="popupvLogin" ref="popupvLogin" type="bottom" />
		<!-- 共用底部 -->

		<!-- 共用底部end1 -->
	</view>
</template>
<script>
	import {oss_host} from '@/config/config.js';
	import Vue from 'vue'
	import store from '@/store/index.js';
	// 公共底部
	import btabbar from '@/components/indexBottomTable/bottomtabbar.vue'
	import bubblePopup from '@/components/tui-bubble-popup/tui-bubble-popup.vue'
	import F2 from '@/js_sdk/uni-f2/f2.min.js'
	function wrapEvent(e) {
	  if (!e) return
	  if (!e.preventDefault) {
	    e.preventDefault = function() {}
	  }
	  return e
	}


	let chart = null

	import {
		mapGetters
	} from 'vuex';

	const lineCharts = {},
		optionAs = {};
	export default {
		components: {
			btabbar,
			bubblePopup
		},
		computed: {
			cWidth() {
				return uni.upx2px(this.width);
			},
			cHeight() {
				return uni.upx2px(this.height);
			},
			//注册网络状态
			...mapGetters(['netWorkType', 'loginStatus'])
		},
		data() {
			return {
				showTip:true,
				echartsData:[],
				showEchart:true,
				showBottomMenu:true,
				isBind:false,
				group_id:'',
				userAge:'',
				userName:'',
				width: 750,
				height: 500,
				canvasId: 'canvasMix',
				labelKey: 'label',
				valueKey: 'value',
				//图标

				showUchart: false,
				avatarUrl: '',
				nickName: '',
				OSS_HOST: oss_host,
				member_id: '',
				currentRole: '',
				visible: true,
				indicatorStyle: `height: 50px;`,
				// 骨架屏
				skeletonShow: false,
				lineChartData: {

					label: [],
					value: [{
						name: '高压',
						data: []
					}, {
						name: '低压',
						data: []
					}]

				},
				yAxisAs: {
					// disabled:false,
					max: 200,
					formatter: {
						type: 'number', //type:number percent String,额外参数:fixed:NUmber,name:String
						fixed: 0,
						name: ''
					}

				},
				family:0,
				data: {
					list: [],
					user: {},
					user_member: [],
				  
				},
				user_id:0
			}
		},

		onLoad() {


		},
		created() {

		},
		mounted() {
			let _this = this;
			this.$nextTick(function() {
				if (_this.loginStatus) {
					// _this.getList();
				}

				//_this.lineChart()
			})
		},
		onShow() {
			let _this = this;
			// this.beforeSevenDay();
			// this.checkBind()

			this.group_id =uni.getStorageSync('dev_group_id')?uni.getStorageSync('dev_group_id'):0;

			this.$nextTick(function() {
				if (_this.loginStatus) {
					_this.getList();
				}

				//_this.lineChart()
			})

		},
		methods: {
			toFamily(){
					let _this = this
						if (this.family != 0) { 
							_this.$refer.setVilit('/blood-pressure/family/detail') 
						} else {
						 	_this.$refer.setVilit('/blood-pressure/family/index')
						}
						
						let data = {
							active_type:1,
							user_id:_this.user_id
						}
				 
						let callback = function(url) {
							 
						}
						
						_this.$refer.toUrl(callback,data)
			 
			},
			initChart() {

				const query = uni.createSelectorQuery().in(this);
				query.select('.f2-canvas')
				  .fields({
				    node: true,
				    size: true
				  })
				  .exec(res => {
				    const { node, width, height } = res[0];
				    const context = node.getContext('2d');
				    const pixelRatio = wx.getSystemInfoSync().pixelRatio;
				    // 高清设置
				    node.width = width * pixelRatio;
				    node.height = height * pixelRatio;
				    const config = { context, width, height, pixelRatio };

					// // 实例化chart
					const chart = new F2.Chart(config)
					chart.legend(false)
					// Tooltip 配置
					chart.tooltip({
					  showTitle: true, // 展示  tooltip 的标题
					  layout: 'vertical'
					});
					chart.scale('value', {
						min: 0,
					    ticks: [ 0, 60, 120, 180, 240 ],
					});
					//数据源
					chart.source(this.echartsData);
					chart.line().position('date*value').color('type');
					chart.render();

				    if (chart) {
				      this.chart = chart;
				      this.canvasEl = chart.get('el');
				    }
				  });
			},
			// 判断是否绑定设备
			checkBind(){
				let _this = this
				let opt = {
					url: '/user/health_center',
					data: {
						factory:'scian'
					},
					success: function(res) {
						// console.log(res)
						if (res.status == 1) {
							if(!res.data){
								_this.isBind=false;
							}else{
								_this.isBind=true;
							}


						} else {

						}

					}
				};
				if (this.loginStatus) {
					this.$service.GetApi(opt) //网络
				}
			},
			toIndex() {
				let _this = this
				this.$refer.setVilit('/pages/index/index')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}

				this.$refer.toUrl(callback, 'reLaunch')
			},
			toManager() {
				let _this = this
				this.$refer.setVilit('/packageWeight/pages/healthy/user')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				var data = {
					member_id: _this.data.user.id,

				}
				this.$refer.toUrl(callback, data)
				return
			},
			getList() {
				let _this = this

				this.skeletonShow = true;
				_this.avatarUrl = uni.getStorageSync('avatarUrl');
				_this.nickName = uni.getStorageSync('nickName')
				_this.group_id = uni.getStorageSync('group_id')?uni.getStorageSync('group_id'):'';
				console.log("****list:",_this.group_id)
				let opt = {
					url: '/blutdruck_check/index',
					data: {
						group_id:_this.group_id,
						product_type:1,
						factory:'scian'
					},
					success: function(res) {
						// console.log(res)
						let k = parseInt(_this.group_id)
						if (res.status == 1) {
							_this.skeletonShow = false;
							_this.group_id=_this.group_id!=''?_this.group_id:0;
							let k = _this.group_id;
							console.log('****k:',k)
							_this.data.list = res.data;
							_this.data.user_member = JSON.parse(JSON.stringify(res.data.user_member));

							_this.userName=_this.data.user_member[k].nickname;

							_this.userAge=_this.data.user_member[k].age
							_this.member_id=JSON.parse(JSON.stringify(_this.data.user_member[k].id))

							_this.isBind = res.data.isBindDev
							_this.data.user = JSON.parse(JSON.stringify(_this.data.user_member[k])); //深拷贝
							// _this.group_id=JSON.parse(JSON.stringify(_this.data.user_member[0])).group_id;
							_this.echartsData = res.data.echarts.value;
							 _this.family = res.data.family
							 _this.user_id = res.data.user_id
							 uni.setStorage({ 
								 key:'login_uid',
								 data:res.data.user_id
							 })
							// if(k>0){
							// 	_this.tabList()
							// }
							_this.initChart()


						} else {

						}

					}
				};
				if (this.loginStatus) {
					this.$service.GetApi(opt) //网络
				}

			},
			beforeSevenDay() {
				let aa = [0, -1, -2, -3, -4, -5, -6];
				var date1 = new Date(),
					time1 = date1.getFullYear() + "-" + (date1.getMonth() + 1) + "-" + date1.getDate(); //time1表示当前时间
				var date2 = new Date(date1);
				let time2 = []
				time2 = aa.map(function(row) {
					date2.setDate(date1.getDate() + row);
					// date2.getFullYear()+"-"+(date2.getMonth()+1)+"-"+date2.getDate();
					return (date2.getMonth() + 1) + "/" + date2.getDate();
				})
				this.lineChartData.label = time2;




			},
			pageArticleDetail(id) {
				let _this = this
				this.$refer.setVilit('/packageArticle/pages/healthy-article/article_detail')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				var data = {
					id: id
				}
				this.$refer.toUrl(callback, data)
				return
			},
			tabList() {
				// this.getList()
				let _this = this
				let opt = {
					url: '/blutdruck_check/index',

					data: {
						group_id: _this.group_id,

						product_type:1,
						factory: "scian"

					},
					success: function(res) {
						// console.log(res)
						if (res.status == 1) {
							_this.skeletonShow = false;
							_this.data.list = res.data;
							let val = res.data.echarts.value;
							let sp = val.map(res => {

								return res.sp
							})
							let dp = val.map(res => {
								return res.dp
							})
							let arr = [{
									name: '高压',
									data: sp
								},
								{
									name: '低压',
									data: dp
								}
							]
							_this.$set(_this.lineChartData, 'label', res.data.echarts.dateformat)
							_this.$set(_this.lineChartData, 'value', arr)



							_this.echartsData = res.data.echarts.value;
							// _this.lineChart()
							_this.initChart()

							// _this.data.user_member = res.data.user_member;
							// _this.data.user = _this.data.user_member[0];

							console.log(_this.data.list)
						} else {

						}

					}
				};
				if (this.loginStatus) {
					this.$service.GetApi(opt) //网络
				}

			},
			// 切换角色
			changeRole() {
				this.showEchart=false;
				this.showBottomMenu=false;
				this.$refs.roles.open()

			},
			cancelRole(){
				this.$refs.roles.close()

				this.showEchart=true;
				this.showBottomMenu=true;
				this.tabList()
			},
			selectRole(row) {
				this.showEchart=true;

				this.userName = JSON.parse(JSON.stringify(row.nickname));
				this.userAge = JSON.parse(JSON.stringify(row.age));
				this.member_id = row.id;
				this.group_id=row.group_id;
				uni.setStorageSync('group_id',this.group_id);
				console.log('*****hc:',uni.getStorageSync('group_id'));
				this.$refs.roles.close();
				this.showBottomMenu=true;
				this.tabList()
				uni.setStorageSync('dev_group_id', this.group_id)
				

			},
			// 血压测试结果说明
			introduction() {
				let _this = this
				this.$refer.setVilit('test_result')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				var data = {
					product_type:1
				}
				this.$refer.toUrl(callback, data)
				return
			},
			// 文章推荐
			pageArticleList() {
				let _this = this
				this.$refer.setVilit('/packageArticle/pages/healthy-article/article_list')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				var data = {
					product_type:1
				}
				this.$refer.toUrl(callback, data)
				return
			},

			// 开启健康计划
			enableHealthyPlan() {
				let _this = this
				this.$refer.setVilit('/packageHealthy/pages/device/blood-pressure/healthy_plan/healthy_plan')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				var data = {
					member_id: _this.data.user.id,
					date: '2021-05-14'

				}
				this.$refer.toUrl(callback, data)
				return
			},

			// 绑定设备
			bindEquip() {
				let _this = this
				this.$refer.setVilit('/packageHealthy/pages/bind_equip/bind')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				var data = {

				}
				this.$refer.toUrl(callback, data)
				return

			},
			// 更多数据
			moreData() {
				let _this = this
				this.$refer.setVilit('/packageHealthy/pages/device/blood-pressure/data_list/data_list')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				var data = {
					member_id: _this.member_id,
					product_type:1
				}
				this.$refer.toUrl(callback, data)
				return
			},

			// 检测记录
			testRecord() {
				let _this = this
				this.$refer.setVilit('/packageHealthy/pages/test_record/test_record')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				var data = {
					group_id: _this.group_id,
					product_type: 1,
				}
				this.$refer.toUrl(callback, data)
				return
			},

			touchStart(e) {
			  const canvasEl = this.canvasEl
			  if (!canvasEl) {
			    return
			  }
			  canvasEl.dispatchEvent('touchstart', wrapEvent(e))
			},
			touchMove(e) {
			  const canvasEl = this.canvasEl
			  if (!canvasEl) {
			    return
			  }
			  canvasEl.dispatchEvent('touchmove', wrapEvent(e))
			},
			touchEnd(e) {
			  const canvasEl = this.canvasEl
			  if (!canvasEl) {
			    return
			  }
			  canvasEl.dispatchEvent('touchend', wrapEvent(e))
			},
			closeTip(){
				this.showTip=false
			}

		}
	}
</script>

<style lang="scss">
	@import "./index.scss";
</style>
